// pages/addArticle/addArticle.ts
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import { addBlog } from "../../utils/api";
let tempImageArr: any = [];
let tempImageReadyArr: any = [];
let index = 0;
let baseURL = "http://192.168.0.101:3000";
// let baseURL = "https://www.lv666.top:3384";
Page({
  data: {
    contentHeight: 0,
    value: "",
    show: false,
    classification: "请选择适合人群",
    columns: ['男士发型', '女士发型', '儿童发型'],
    imageFileList: null,
    videoFileList: null,
    message: "",
    windowHeight: 0
  },
  // upload
  onUploadInfo() {
    const params: any = {};
    if (this.data.classification == "男士发型") {
      params['classification'] = 2;
    } else if (this.data.classification == "女士发型") {
      params['classification'] = 1;
    } else if (this.data.classification == "儿童发型") {
      params['classification'] = 3;
    }
    params["content"] = this.data.message;
    if (this.data.imageFileList) {
      params["imageUrl"] = tempImageReadyArr;
      params["coverImageUrl"] = tempImageReadyArr[0].thumb;
      params["type"] = 1;
    } else {
      params["videoUrl"] = this.data.videoFileList;
      // @ts-ignore
      params["coverImageUrl"] = this.data.videoFileList[0].thumb;
      params["type"] = 2;
    }
    addBlog(params).then((res) => {
      if (res) {
        Toast.success("发表成功");
        this.setData({
          imageFileList: null,
          videoFileList: null,
          classification: "请选择适合人群",
          message: " "
        })
      }
    })
  },
  // 删除图片
  onDeleteImage(event: any) {
    const { detail } = event;
    const index = detail.index;
    const tempArr = this.data.imageFileList || [];
    const newTempArr: any = [];
    tempArr.forEach((element, i) => {
      if (index != i) {
        newTempArr.push(element);
      }
    });

    this.setData({
      imageFileList: newTempArr.length ? newTempArr : null
    })

  },
  // 删除视频
  onDeleteVideo(event: any) {
    const { detail } = event;
    const index = detail.index;
    const tempArr: any = this.data.videoFileList || [];
    const newTempArr: any = [];
    tempArr.forEach((element: any, i: any) => {
      if (index != i) {
        newTempArr.push(element);
      }
    });
    this.setData({
      videoFileList: newTempArr.length ? newTempArr : null
    })
  },
  // 输入事件绑定
  // @ts-ignore
  onChangeMessage({ detail }) {
    this.setData({
      message: detail.value
    })
  },
  readyImage(event: any) {
    tempImageArr = [];
    tempImageReadyArr = [];
    tempImageArr = event.detail.file;
    this.afterReadImage();
  },
  // 图片上传
  afterReadImage() {
    const element = tempImageArr[index];
    if (!element) {
      this.setData({
        imageFileList: tempImageArr
      }, () => {
        index = 0;
      })
      return;
    }
    this.setData({
      ["imageFileList[" + index + "]"]: {
        thumb: element.url,
        url: element.url,
        isImage: true,
        status: 'uploading',
        message: '上传中'
      }
    }, () => {
      this.imageUploadFn(element.url);
    })
  },
  imageUploadFn(url: any) {
    wx.uploadFile({
      url: `${baseURL}/api/file/uploadImage`,
      filePath: url,
      name: 'image',
      success: (res: any) => {
        let data = JSON.parse(res.data);
        tempImageReadyArr.push({
          thumb: data.data[0].thumbnail,
          url: data.data[0].path,
          status: 'done',
          isImage: true,
        });
        index++;
        this.afterReadImage();
      }
    });
  },
  // 视频上传
  afterReadVideo(event: any) {
    const obj = event.detail.file;
    this.setData({
      // @ts-ignore
      videoFileList: [{
        thumb: obj.thumb,
        url: obj.url,
        isVideo: true,
        status: 'uploading',
        message: '上传中'
      }]
    })
    // @ts-ignore
    this.videoUploadFn(event.detail.file.duration, this.data.videoFileList[0].url);
  },
  async videoUploadFn(duration: number, url: string) {
    wx.uploadFile({
      url: `${baseURL}/api/file/uploadVideo`,
      filePath: url,
      name: 'video',
      timeout: 1000 * 60 * 5,
      formData: { duration },
      success: (res: any) => {
        const data = JSON.parse(res.data).data;
        setTimeout(() => {
          // @ts-ignore
          this.setData({
            // @ts-ignore
            videoFileList: [{
              thumb: data.captureCoverImage,
              url: data.finallyUrlM3u8,
              isVideo: true,
              status: 'done'
            }]
          })
        }, 2000)
      },
      fail: (err) => {
        console.log(err)
      }
    });
  },
  // 图片上传前验证
  beforeReadImage(event: any) {
    const { file, callback } = event.detail;
    // @ts-ignore
    file.forEach(element => {
      if (element.type === 'image') {
        callback(true)
      } else {
        Toast.fail('文件格式不符合');
      }
    });
  },
  // 视频上传前验证
  beforeReadVideo(event: any) {
    const { file, callback } = event.detail;
    if (file.type === 'video' && file.size <= 31457280000) {
      callback(true);
    } else {
      Toast.fail('文件格式不符合/大于300M');
    }
  },
  // 确定下拉属性
  onConfirm(event: any) {
    // @ts-ignore
    const { picker, value, index } = event.detail;
    this.setData({
      classification: value
    })
    this.onClose();
  },
  // 取消选择下拉
  onCancel() {
    this.onClose();
  },
  // 显示下拉列表
  showPopup() {
    this.setData({ show: true });
  },
  // 关闭下拉列表
  onClose() {
    this.setData({ show: false });
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    const BC = wx.getMenuButtonBoundingClientRect();
    const { windowHeight } = wx.getWindowInfo();
    console.log(BC);
    this.setData({
      contentHeight: BC.top + BC.height + 20,
      windowHeight
    })
  }
})